<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/system/user' }">系统管理</el-breadcrumb-item>
            <el-breadcrumb-item :to="{ path: '/system/user' }">用户管理</el-breadcrumb-item>
        </el-breadcrumb>
         <!-- 搜索筛选 -->
        <el-form :inline="true" :model="searchUser" class="user-search">  
            <!-- <el-form-item label="搜索：">
                <el-input size="small" v-model="searchUser.names" placeholder="输入用户名称"></el-input>
            </el-form-item> -->
            <!-- <el-form-item>
                <el-select v-model="searchUser.role" placeholder="请选择角色">
                    <el-option
                    v-for="item in roleList"
                    :key="item.role_id"
                    :label="item.role_name"
                    :value="item.role_id">
                    </el-option>
                </el-select>
            </el-form-item> -->
            <el-form-item>
                <!-- <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button> -->
                <el-button size="small" type="primary" icon="el-icon-plus" @click="addHandleEdit">添加</el-button>
            </el-form-item>
        </el-form>
       <!--列表-->
        <el-table size="small" :data="listData" highlight-current-row v-loading="loading" border element-loading-text="拼命加载中" style="width: 100%;">
            <el-table-column sortable prop="user_name" label="用户名称" width="150">
            </el-table-column>
            <el-table-column sortable prop="another_name" label="用户昵称" width="150">
            </el-table-column>
            <el-table-column sortable prop="password" label="密码" width="150">
            </el-table-column>
             <el-table-column sortable prop="email" label="邮箱" width="200">
            </el-table-column>
            <el-table-column sortable prop="role_id" label="身份" width="100">
            </el-table-column>
            <!-- <el-table-column sortable prop="store" label="状态" width="100">
            </el-table-column> -->
             <el-table-column sortable prop="user_state_id" label="用户状态" width="100">
            </el-table-column>
            
            
            <el-table-column align="center" label="操作" min-width="300" fixed="right">
                <template slot-scope="scope">
                    <el-button size="mini" v-if="scope.row.role_id != 3" @click="resetPsd(scope.$index, scope.row)" type="info">重置密码</el-button>
                    <el-button size="mini" v-if="scope.row.role_id != 3 && scope.row.user_state_id == 1" @click="freezeUser(scope.$index, scope.row)" type="primary">冻结</el-button>
                     <el-button size="mini" v-if="scope.row.role_id != 3 && scope.row.user_state_id == 2" @click="unfreezeUser(scope.$index, scope.row)" type="success">解冻</el-button>
                    <el-button size="mini" v-if="scope.row.role_id != 3 && scope.row.role_id != 2" type="danger" @click="deleteUser(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
         <!-- 分页组件 -->
        <el-pagination class="page-box" 
            @size-change="handleSizeChange" 
            @current-change="handleCurrentChange" 
            background 
            :current-page="currentPage" 
            :page-sizes="[10, 20, 30, 40]" 
            :page-size="pageSize"  
            :total="total">
        </el-pagination>
        <!-- 编辑界面 -->
        <el-dialog :title="title" :visible.sync="editFormVisible" width="30%" @click="closeDialog">
            <el-form label-width="120px" :model="editForm" :rules="rules" ref="editForm">
                <el-form-item label="用户名" prop="user_name">
                    <el-input size="small" v-model="editForm.user_name" auto-complete="off" placeholder="请输入用户名"></el-input>
                </el-form-item>
                 <el-form-item label="昵称" prop="another_name">
                    <el-input size="small" v-model="editForm.another_name" auto-complete="off" placeholder="请输入昵称名称"></el-input>
                </el-form-item>
               <!-- 身份 -->
               <el-form-item label="身份" prop="role_id">
                    <el-select v-model="editForm.role_id" placeholder="请选择身份">
                        <el-option
                            v-for="item in roleList"
                            :key="item.role_id"
                            :label="item.role_name"
                            :value="item.role_id">
                            </el-option>
                        <!-- <el-option label="用户" value="1"></el-option>
                        <el-option label="商家" value="2"></el-option>
                        <el-option label="管理员" value="3"></el-option> -->
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="small" @click="closeDialog">取消</el-button>
                <el-button size="small" type="primary" :loading="loading" class="title" @click="submitForm('editForm')">保存</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import axios from 'axios'
import { newStampChangeFormat } from "./../../untils/index"
export default {
    // 默认子路由 不能有name属性
    name: "User",
    data() {
        return {

            roleList:[],  //角色列表
            loading: false, //是显示加载,
            pageSize: 6,   //页数
            currentPage: 1,  //当前页,
            total: 2,  //总页数
            editFormVisible: false, //控制编辑页面显示与隐藏
            dist: "", //区别唯一标识符  add 添加  del删除  edit编辑
            distNum: "",  //编辑的第几条数据
            searchUser: {
                names: "",
                // role: ""
            },
            listData: [ 
                // {
                //     user_name: "user1",
                // another_name
                //     password: "psd1",
                //     role_id: "身份1",
                //     store: "修改人1"
                // },
                // {
                //     "user_name": "admin",
                // another_name
                //     "password": 123456,
                //     "role_id": 1,
                //     "store": 1
                // }
            ],
            editForm: {
                user_name: '',
                another_name: '',
                password: '',
                role_id: ''
            },
            title: '添加',
            rules: {
                user_name: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
                another_name: [{ required: true, message: '请输入用户昵称', trigger: 'blur' }],
                password: [{ required: true, message: '请输入用户密码', trigger: 'blur' }],
                role_id: [{ required: true, message: '请输入身份', trigger: 'blur' }]
            },
            searchArr: [],
            dataStore: [],  //存储旧的数据
        }
    },
    methods: {
        search() {
            let user_name = this.searchUser.names;
            if (!user_name ) {
                this.handleCurrentChange(1);
                this.total = this.dataStore.length;
                return;
            }
            let newArr = [];
            let reg = new RegExp(user_name);
            this.dataStore.forEach(e => {    
                if (reg.test(e.user_name) ) {
                    newArr.push(e);
                }
            })
            this.listData = newArr;
            this.total = newArr.length;
        },
        //add
        addHandleEdit() {
            this.clearData();
            this.dist = "add";
            this.editFormVisible = true;
            

        },
        //重置密码
        resetPsd(index, row) {
            axios({
                method: "post",
                url: "/user/reset",
                data: {
                    user_id: row.user_id,
                    // user_state: row.user_state
                }
            }).then(
                res => {
                    console.log('reset', res.data);
                    if (res.data.code == "200") {
                        //重置成功
                         this.$message({
                            message: '密码重置成功',
                            type: 'success'
                        });
                    } else {
                        //失败
                        this.$message({
                            showClose: true,
                            message: '重置失败，请重试',
                            type: 'warning'
                        });
                    }
                }
            )
            //页面更新
            this.listData[index].password = '123456';

            // console.log("重置密码", index, row);
            
        },
        freezeUser(index, row) {
            console.log("冻结用户")
            axios({
                method: "post",
                url: "/user/frezz",
                data: {
                        user_id: row.user_id,
                        user_state_id: 2
                }
            }).then(
                res => {
                    console.log(res.data);
                    if(res.data == true) {
                        this.$message({
                            message: '冻结成功',
                            type: 'success'
                        });
                        this.listData[index].user_state_id = 2;
                        // window.location.reload();
                    } else {
                        this.$message({
                            showClose: true,
                            message: '冻结失败，请重试',
                            type: 'warning'
                        });
                    }
                }
            )
        },
        // 解冻
        unfreezeUser(index, row) {
            this.dist = "unfreezeUser";
            console.log("解冻用户") 
            axios({
                method: "post",
                url: "/user/frezz",
                data: {
                        user_id: row.user_id,
                        user_state_id: 1
                }
            }).then(
                res => {
                    console.log(res.data);
                    if(res.data == true) {
                        this.$message({
                            message: '解冻成功',
                            type: 'success'
                        });
                        this.listData[index].user_state_id = 1;
                        
                    } else {
                        this.$message({
                            showClose: true,
                            message: '解冻失败，请重试',
                            type: 'warning'
                        });
                    }
                }
            )

            
            
        },
        handleSizeChange(val) {
           this.pageSize = val 
        },
        handleCurrentChange(val) {
            this.currentPage = val;
            let pageSize = this.pageSize;
            let da = this.dataStore;
            let i = (val - 1) * pageSize;
            let arr = da.slice(i , i + pageSize);
            this.listData = arr;
        },
        //提交保存
        submitForm(editData) {
            this.$refs[editData].validate(valid => {
                // console.log(newStampChangeFormat());
                if (valid) {
                    if (this.dist == "add") {
                        // console.log("submitForm", this.editForm.user_name)
                        //将用户数据添加
                        let names = this.editForm.user_name;
                        let another_name = this.editForm.another_name;
                        let ident = this.editForm.role_id;
                        axios({
                            method: "post",
                            url: "/user/add3",
                            data: {
                                user_name: names , //用户名称
                                another_name: another_name,   //用户昵称
                                role_id: ident,
                            }
                        }).then(
                            res => {
                                if(res.data.code == 200) {
                                    
                                    this.dataStore.push({
                                        user_name: names , //用户名称
                                        another_name: another_name,   //用户昵称
                                        role_id: ident,
                                        user_state_id: 1
                                    })
                                    this.total += 1;

                                    this.$message({
                                        message: '注册成功',
                                        type: 'success'
                                    });
                                    location.reload(true); // 强制从服务器刷新页面


                                } else if(res.data.code == 302) {
                                    this.$message({
                                        message: '该用户已存在',
                                        type: 'warning'
                                    });
                                } else {
                                    this.$message({
                                        message: '注册失败',
                                        type: 'warning'
                                    });
                                }
                            }
                        )

                        this.listData.push({
                            user_name: this.editForm.user_name,  //用户名称
                            another_name: this.editForm.another_name,  //用户昵称
                            password: this.editForm.password,            //密码
                            role_id:  this.editForm.role_id,
                            user_state_id: 1
                        })

                    } else if(this.dist == "edit") {
                        // console.log(this.listData[this.distNum])
                        // this.listData[this.distNum].user_name = this.editForm.user_name;
                        // this.listData[this.distNum].another_name = this.editForm.another_name
                
                        // this.listData[this.distNum].password = this.editForm.password;
                        // this.listData[this.distNum].role_id = this.editForm.role_id;
                        
                    }
                    
                    //清空内容
                    this.clearData();
                    //关闭dialog
                    this.editFormVisible = false;
                    
               


                } else {
                    return false
                }
            })
        },
        //关闭dialog
        closeDialog() {
            this.editFormVisible = false;
            //数据清空
            this.clearData();
           
        },
        //删除
        deleteUser(index, row) {
            this.dist = "del";
            this.$confirm('是否删除该用户？该操作不可逆！', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    axios({
                        method: "post",
                        url: "/user/del",
                        data: {
                            user_id: row.user_id
                        }
                    }).then(
                        res => {
                            if(res.data) {
                                this.$message({
                                    message: '删除成功',
                                    type: 'success'
                                });
                                this.total -= 1;
                                let position = this.pageSize * (this.currentPage - 1 ) + index;
                                // console.log(index, this.pageSize * (this.currentPage - 1 ) + index)
                                this.listData.splice(index, 1);
                                this.dataStore.splice(position, 1);
                                this.handleCurrentChange(this.currentPage); 
                            } else if (res.data.code == 407) {
                                this.$message({
                                    message: '超级管理员不能删除',
                                    type: 'warning'
                                });
                            } else {
                                this.$message({
                                    message: '删除失败',
                                    type: 'warning'
                                });
                            }
                        }
                    )

                   
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });          
                });
            // console.log(index, row);
            //根据商品代码检索到对应数据remove  splice
            
               
                    // //找到商品
                    
                    // this.$message({
                    //     showClose: true,
                    //     message: '删除成功',
                    //     type: 'success'
                    // });
               
                    
                
            
            
        },
        clearData() {
            this.editForm.user_name = "";
            this.editForm.another_name = "";
            this.editForm.password = "";
            this.editForm.role_id = "";
        },
        getUserInfo() {
            axios.post("/user/info")
            .then(
                res => {
                    console.log(res.data)
                    this.dataStore = res.data;
                    this.handleCurrentChange(1);
                    // this.listData = res.data;
                    this.total = res.data.length;
                    // console.log(res.data)
                }
            )
            //mock模拟的用户数据
            // axios.post("/system/user")
            //     .then(
            //         res => {
            //             this.dataStore = res.data.data;
            //             this.listData = res.data.data;
            //             console.log(res.data.data)
            //         }
            //     )
        },
        getRoleList() {
            axios.get("/role/list")
                .then(
                    res => {
                        this.roleList = res.data;
                        console.log(res.data);
                    }
                )
        }
    },
    created() {
        this.getUserInfo();  //获取user列表
        this.getRoleList(); //获取权限列表

    }
}
</script>

<style scoped>
.el-form {
    margin: 0;
    padding: 0;
    text-align: left;
}
.el-pagination {
    margin-top: 20px;
}
.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}
</style>
  